package com.accp.wxmp.util;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;


@SuppressWarnings("deprecation")
public class HttpUtil {
	/**
	 * 发送http请求， 参数是json串，获取返回值，返回值是json
	 * 
	 * @param url url
	 * @param jsonParam json串
	 * @return 返回值是json
	 */
	public static String getJsonFromUrlPost(String url, String jsonParam) {
		String getJson = "";
		HttpClient httpclient = null;
		HttpPost httpPost = null;
		try {
			httpclient = new DefaultHttpClient();
			httpPost = new HttpPost(url);
			StringEntity entity = new StringEntity(jsonParam, "utf-8");// 解决中文乱码问题
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
			httpPost.setEntity(entity);
			HttpResponse response = httpclient.execute(httpPost);
			response.getStatusLine().getStatusCode();
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			String str = "";
			while ((str = rd.readLine()) != null) {
				getJson += str;
			}
			System.out.println("返回值：" + getJson);
			//logger.info("返回值：" + getJson);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			//logger.info(e.getMessage());
		} finally {
			httpPost.abort();
			httpPost.releaseConnection();
		}
		return getJson;
	}

	/**
	 * 根据url请求服务器，获取json
	 * 
	 * @param url
	 * @return
	 */
	public static String getJsonFromUrl(String url) {
		System.out.println("请求url：" + url);
		//logger.info("请求url：" + url);
		String getJson = "";
		HttpClient httpclient = null;
		HttpGet httpgets = null;
		try {
			httpclient = new DefaultHttpClient();
			httpgets = new HttpGet(url);
			httpgets.addHeader("Content-Type", "text/html;charset=UTF-8");
			HttpResponse response = httpclient.execute(httpgets);
			response.getStatusLine().getStatusCode();
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
			String str = "";
			while ((str = rd.readLine()) != null) {
				getJson += str;
			}
			System.out.println("返回值：" + getJson);
		//	logger.info("返回值：" + getJson);
		} catch (Exception e) {
			System.out.println(e.getMessage());
			//logger.info(e.getMessage());
		} finally {
			assert httpgets != null;
			httpgets.abort();
			httpgets.releaseConnection();
		}
		return getJson;
	}





}
